module PagerHelper

  def prev_page(title, options = {}, html_options = {}, *params)
    if @pager.page && @pager.page > 1
      options.merge! :page => @pager.page - 1
      html_options.reverse_merge! :class => 'prev_page'
      link_to title, options, html_options # TODO - BK - Figure out why params isn't working here
    end
  end
  
  def next_page(title, options = {}, html_options = {}, *params)
    if @pager.limit < @pager.count && @pager.page != @pager.last_page
      options.merge! :page => (@pager.page || 1) + 1
      html_options.reverse_merge! :class => 'next_page'
      link_to title, options, html_options # TODO - BK - Figure out why params isn't working here
    end
  end
  
  def all_pages(options = {}, html_options = {}, *params)
    out = ''
    if @pager.limit < @pager.count
      (1..@pager.last_page).each do |i| 
        options.merge! :page => i
        class_name = if i == @pager.page
          if html_options.has_key? :class
            { :class => html_options[:class] + "_selected" }
          else
            { :class => "number_page_selected" }
          end
        else
          { :class => "number_page" }
        end
        out += link_to(i, options, html_options.merge(class_name)) + ' ' # TODO - BK - Figure out why params isn't working here
      end
    end
    out
  end
  
  def has_pages?
    yield if @pager && @pager.limit < @pager.count
  end
  
  class Pager
    attr_accessor :limit
    attr_accessor :count
    attr_accessor :page
    
    
    def initialize(limit, count, page = nil)
      self.limit = limit.to_i
      self.count = count.to_i
      self.page = (page ? page.to_i : 1)
    end
    
    def find_options
      { :limit => limit, :offset => offset}
    end
    
    def offset
      (page - 1) * limit
    end
    
    def last_page
      count.zero? ? 1 : (q,r=count.divmod(limit); r==0? q : q+1)
    end
    
  end

end
